@inherits PartialViewMacroPage
@using Umbraco.Cms.Web
@using Umbraco.Cms.Web.Macros
@using Umbraco.Framework
@{ 
    //Maximum level you want to loop down to 
    var maxLevel = String.IsNullOrEmpty(Model.MacroParameters.maxLevel) ? 8 : Convert.ToInt32(Model.MacroParameters.maxLevel);

    //Get the current page
    var currentPage = DynamicModel;

    //Will walk up the tree to the last ancestor node aka RootNode
    var rootNode = currentPage.AncestorsOrSelf.Last();

    //Check if the rootNode is the currentPage (selected)
    var rootIsSelected = currentPage.Id == rootNode.Id;
        
    <nav id="top-nav">
        <ul class="level-@(rootNode.Level)">
            <li>
                @* Add CSS class selected if rootIsSelected *@
                <a href="@rootNode.Url" class="@(rootIsSelected ? "selected" : "")">@rootNode.Name</a>

                @* Display children on  rootNode *@
                @childPages(rootNode.Children, maxLevel)
            </li>
        </ul>
    </nav>
    
}


@helper childPages(dynamic pages, int endRenderLevel)
{
    //Check we have pages to loop through
    if (pages.Any())
    {
        //Get the navigation level
        var naviLevel = pages.First().Level;

        if (naviLevel <= endRenderLevel)
        {
        <ul class="level-@(naviLevel)">
            @foreach (var page in pages)
            {
                //Check the page is not hidden with umbracoNaviHide
                if (page.umbracoNaviHide != "True")
                {                
                    //Get the page ID in the loop as a HiveID
                    HiveId pageID = page.Id;

                    //Check if the current page or any of the ancestor pages contain the page ID and retrun a boolean
                    var isSelected = Model.CurrentPage.AllAncestorIdsOrSelf().Contains(pageID);
                    
                    <li>
                        @* Add CSS class selected if isSelected *@
                        <a href="@page.Url" class="@(isSelected ? "selected" : "")">
                            @page.Name
                        </a>

                        @* if the current page has any children *@
                        @if (page.Children.Any())
                        {
                            @childPages(page.Children, endRenderLevel);
                        }
                    </li>
                }
            }
        </ul>
        }
    }    
}
